﻿namespace IntellectShop.Common
{
	using System.Collections.Generic;
	using System.Linq;

	public partial class SingleTag
	{
		public static List<SingleTag> RetrieveAll()
		{
			using (DB.IntellectShopDataContext dataContext = new DB.IntellectShopDataContext(Common.Globals.ConnectionString))
			{
				var query =
							from tags in dataContext.SingleTags
							orderby tags.SortingID descending, tags.Tag
							select tags;

				return query.Select(x => new SingleTag()
				{
					Tag = x.Tag,
					SortingID = x.SortingID
				}).ToList<SingleTag>();
			}
		}

		public static List<Common.Commodity> RetrieveCommodities(string tag)
		{
			using (DB.IntellectShopDataContext dataContext = new DB.IntellectShopDataContext(Common.Globals.ConnectionString))
			{
				var query = (
					from tags in dataContext.TagsSets
					where tags.Tag == tag && tags.Commodity.Closed == null
					orderby tags.Commodity.SortingID descending, tags.Commodity.CommodityID
					select tags.Commodity).Distinct();

				return query.Select(x => new Common.Commodity()
				{
					CommodityID = x.CommodityID,
					Code = x.Code,
					Created = x.Created,
					CreatedBy = x.CreatedBy,
					Description = x.Descr,
					Name = x.Name,
					Price = new Common.Money { Amount = (x.Price.HasValue ? x.Price.Value : 0), Currency = Currency.RUB },
					SortingID = x.SortingID,
					Updated = x.Updated,
					UpdatedBy = x.UpdatedBy
				})
				.ToList<Common.Commodity>();
			}
		}

		public static void Delete(string tag)
		{
			using (DB.IntellectShopDataContext dataContext = new DB.IntellectShopDataContext(Common.Globals.ConnectionString))
			{
				var tagsSetDB =
					from tags in dataContext.TagsSets
					where tags.Tag == tag
					select tags;
				dataContext.TagsSets.DeleteAllOnSubmit(tagsSetDB);
				dataContext.SubmitChanges();

				var singleTagsDB =
					from stag in dataContext.SingleTags
					where stag.Tag == tag
					select stag;
				dataContext.SingleTags.DeleteAllOnSubmit(singleTagsDB);
				dataContext.SubmitChanges();
			}
		}

		public static SingleTag RetrieveByTag(string tag)
		{
			using (DB.IntellectShopDataContext dataContext = new DB.IntellectShopDataContext(Common.Globals.ConnectionString))
			{
				var singleTag = (
							from stag in dataContext.SingleTags
							where stag.Tag == tag
							select stag).SingleOrDefault();

				return singleTag == null ? null : new SingleTag() { Tag = singleTag.Tag, SortingID = singleTag.SortingID };
			}
		}

		public void Update()
		{
			using (DB.IntellectShopDataContext dataContext = new DB.IntellectShopDataContext(Common.Globals.ConnectionString))
			{
				var singletagDB = dataContext.SingleTags.SingleOrDefault(x => x.Tag == this.Tag);
				singletagDB.SortingID = this.SortingID;
				dataContext.SubmitChanges();
			}
		}

	}
}
